
<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <avue-crud
        ref="crud"
        :option="tableOption"
        :data="list"
        :page="page"
        v-model="form"
        :table-loading="listLoading"
        :before-open="handleOpenBefore"
        @on-load="getList"
        @search-change="handleFilter"
        @refresh-change="handleRefreshChange"
        @row-update="update"
        @row-save="create">

        <template slot="menuLeft">
          <el-button
            v-if="unitManager_btn_add"
            class="filter-item"
            type="primary"
            icon="el-icon-edit"
            @click="handleCreate">添加
          </el-button>
        </template>
        <template slot="dsScopeForm" slot-scope="scope">
          <div v-if="form.dsType == 1">
            <el-tree
              ref="scopeTree"
              :data="dsScopeData"
              :check-strictly="true"
              :props="defaultProps"
              :default-checked-keys="checkedDsScope"
              class="filter-tree"
              node-key="id"
              highlight-current
              show-checkbox/>
          </div>
        </template>

        <template
          slot="menu"
          slot-scope="scope">
          <el-button
            v-if="unitManager_btn_edit"
            type="text"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row,scope.index)">编辑
          </el-button>
          <el-button
            v-if="unitManager_btn_del"
            type="text"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(scope.row,scope.index)">删除
          </el-button>
        </template>
      </avue-crud>
    </basic-container>

  </div>
</template>

<script>
import { addObj, fetchList,fetchRoleTree, permissionUpd, putObj } from '@/api/admin/role'
import {unitquery,unitadd,unitdel,unitrepeQuery,delObj} from '@/api/admin/unit'
// import { tableOption,valiuniQuery } from '@/const/crud/admin/unit'
import { fetchTree } from '@/api/admin/dept'
import { fetchMenuTree } from '@/api/admin/menu'
import { mapGetters } from 'vuex'
import { watch } from 'fs'

export default {
  name: 'TableRole',

  data() {
     var valiuniQuery=(rule,value,callback)=>{
        let _fieldUnit=rule.field.toUpperCase();
        if(this.isRow[rule.field]== value){
            return callback();
        }else{
        unitrepeQuery({paraType:rule.field.toUpperCase(),para:value}).then(unitres=>{
            switch (unitres.data.data) {
                case 0:
                    if(_fieldUnit === "NAME") return callback(new Error("已有此用户"))
                    if(_fieldUnit === "CODE") return callback(new Error("此编码已存在"))
                    if(_fieldUnit === "NUMBER") return callback(new Error("此编号已存在"))
                    break;
                case 1:
                    callback();
                    break;
                default:
                break;
            }
        })
        }

    }
    return {
      searchForm: {},

      dsScopeData: [],
      treeData: [],
      checkedDsScope: [],
      defaultProps: {
        label: 'name',
        value: 'id'
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      menuIds: '',
      isRow:'',
      list: [],
      listLoading: true,
      form: {},
      unitId: undefined,
      unitCode: undefined,
      rolesOptions: undefined,
      dialogPermissionVisible: false,
      unitManager_btn_add: false,
      unitManager_btn_edit: false,
      unitManager_btn_del: false,
      tableOption:{
            border: true,
            index: true,
            indexLabel: '序号',
            stripe: true,
            menuAlign: 'center',
            editBtn: false,
            delBtn: false,
            align: 'center',
            addBtn: false,
            viewBtn: true,
            column: [
                {
                    width: 150,
                    label: '序号',
                    prop: 'number',
                    overHidden: true,
                    span: 24,
                    row: true,
                    minRows: 2,
                    rules: [
                        { max: 128, message: '长度在 128 个字符内', trigger: 'blur' },
                        {validator:valiuniQuery ,trigger:'blur'}
                    ]
                },
                {
                    label: '单位名称',
                    prop: 'name',
                    span: 24,
                    rules: [
                        { required: true, message: '单位名称不能为空', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 100 个字符', trigger: 'blur' },
                        {validator:valiuniQuery ,trigger:'blur'}
                    ]
                },{
                    label: '单位简称',
                    prop: 'shortName',
                    span: 24,
                    rules: [
                        { required: true, message: '单位简称不能为空', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                    ]
                }, {
                    width: 120,
                    label: '单位编码',
                    prop: 'code',
                    span: 24,
                    editDisabled: true,
                    rules: [
                        { required: true, message: '单位标识不能为空', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
                        { validator:valiuniQuery, trigger: 'blur' }
                    ]
                }, {
                    width: 120,
                    label: '单位类型',
                    prop: 'unitType',
                    span: 24,
                    type: 'select',
                    dicData: [{
                        label: '总公司',
                        value: '1'
                    }, {
                        label: '分公司',
                        value: '2'
                    }],
                    rules: [
                        { required: true, message: '单位类型不能为空', trigger: 'blur' },
                    ]

                }, {
                    width: 120,
                    label: '医院标识',
                    prop: 'hospitalFlag',
                    span: 24,
                    type: 'select',
                    dicData: [{
                        label: '否',
                        value: 0
                    }, {
                        label: '是',
                        value: 1
                    }],
                    rules: [
                        { required: true, message: '医院标识不能为空', trigger: 'blur' },
                    ]

                }]
        }
    }
  },
  created() {
    this.unitManager_btn_add = this.permissions['sys_unit_add']
    this.unitManager_btn_edit = this.permissions['sys_unit_edit']
    this.unitManager_btn_del = this.permissions['sys_unit_del']
  },

  computed: {
    ...mapGetters(['elements', 'permissions'])

  },
  methods: {
    getList(page, params) {
      this.listLoading = true
      unitquery(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.list = response.data.data.records
        this.page.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleRefreshChange() {
      this.getList(this.page)
    },
    handleFilter(form) {
      this.searchForm = form
      this.getList(this.page, form)
    },
    handleCreate() {
      this.$refs.crud.rowAdd()
    },
    handleOpenBefore(show) {
      fetchTree().then(response => {
        this.dsScopeData = response.data.data
        if (this.form.dsScope) {
          this.checkedDsScope = (this.form.dsScope).split(',')
        } else {
          this.checkedDsScope = []
        }
      })
      show()
    },
    handleUpdate(row, index) {
      this.$refs.crud.rowEdit(row, index)
      this.isRow=row;
    },
    getNodeData(data, done) {
      done()
    },
    handleDelete(row, index) {
      var _this = this
      this.$confirm('是否确认删除名称为"' + row.name + '"' + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(() => {
        this.getList(this.page)
        this.$notify.success('删除成功')
      })
    },
    create(row, done, loading) {
      if (this.form.dsType === 1) {
        this.form.dsScope = this.$refs.scopeTree.getCheckedKeys().join(',')
      }
      unitadd(this.form).then(() => {
        this.getList(this.page)
        done()
        this.$notify.success('创建成功')
      }).catch(() => {
        loading()
      })
    },
    update(row, index, done, loading) {
      unitdel(this.form).then(() => {
        this.getList(this.page)
        done()
        this.$notify.success('修改成功')
      }).catch(() => {
        loading()
      })
    },
  }
}
</script>

<style lang="scss" scoped>
  .el-dialog__wrapper {
  .el-dialog {
    width: 61% !important;
  .dialog-main-tree {
    max-height: 400px;
    overflow-y: auto;
  }
  }
  .el-form-item__label {
    width: 20% !important;
    padding-right: 20px;
  }
  .el-form-item__content {
    margin-left: 20% !important;
  }
  }
</style>
